package com.episode.duetapi.shiro;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.episode.duetapi.exceptionHandle.CustomerException;
import com.episode.duetapi.model.Admin;
import com.episode.duetapi.model.User;
import com.episode.duetapi.service.AdminService;
import com.episode.duetapi.utils.JwtHelper;
import com.episode.duetapi.utils.MD5Util;
import com.episode.duetapi.utils.ResultCode;

public class MyShiroRealm extends AuthorizingRealm {
	
	@Resource
	private AdminService adminService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//获取用户
		Admin user = (Admin) SecurityUtils.getSubject().getPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//获取用户角色
		Set<String> roleSet = new HashSet<String>();
		roleSet.add("100002");
		info.setRoles(roleSet);
		//获取用户权限
		Set<String> permissionSet = new HashSet<String>();
		permissionSet.add("权限添加");
		permissionSet.add("权限删除");
		info.setStringPermissions(permissionSet);
		return info;
	}

	/**
	 * 验证用户身份
	 * */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authToken;
		String username = token.getUsername();
		String password = String.valueOf(token.getPassword());
		
		Admin admin = adminService.loginByUser(username,password);
		if(null == admin) {
			throw new CustomerException(ResultCode.LoginErroe);
		}
		//禁用账户
		if( 0 == admin.getStatus()) {
			throw new LockedAccountException();
		}
		String authorization = JwtHelper.createJWT(admin.getId(), admin.getUsername(), admin.getRoleid());
		admin.setAuthorization(authorization);
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				admin,
				admin.getPassword(),
				admin.getUsername()
				 );
		return authenticationInfo;
	}

}
